﻿using IService.Admin;
using Model.Parameter.Admin;

namespace Service.Admin
{
    public class CustomerService : BaseService<TCustomerinfo>, ICustomerService
    {
        private readonly WebMiscConfig _WebMiscConfig;

        public CustomerService(IUnitOfWorkService unitOfWorkService, IOptions<WebMiscConfig> webMiscConfig) : base(unitOfWorkService)
        {
            _WebMiscConfig = webMiscConfig.Value;
        }

        public async Task<RM_ApiResult> AddOrUpdate(Par_Customerinfo req)
        {
            var par = req.Adapt<TCustomerinfo>();

            if (!string.IsNullOrWhiteSpace(par.Phone) && await Any(o => o.Phone == par.Phone && o.Id != par.Id && o.IsDeleted == false))
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Customer.PhoneExist);
            }

            if (!string.IsNullOrWhiteSpace(par.Email) && await Any(o => o.Email == par.Email && o.Id != par.Id && o.IsDeleted == false))
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Customer.EmailExist);
            }

            if (await Any(o => o.NickName == par.NickName && o.Id != par.Id && o.IsDeleted == false))
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Customer.NickNameExist);
            }

            if (par.Id == 0)
            {
                par.Password = _WebMiscConfig.ResetPassWord;
            }
            else
            {
                if (string.IsNullOrWhiteSpace(req.Password))
                {
                    var old = await Get(o => o.Id == par.Id);
                    if (old != null)
                    {
                        par.Password = old.Password;
                    }
                }
                else
                {
                    par.Password = md5Helper.CalculateMD5Hash(req.Password);
                }
            }

            if (string.IsNullOrWhiteSpace(par.Avatar))
            {
                par.Avatar = _WebMiscConfig.DefaultAvator;
            }

            var result = await AddOrUpdate(par, true);

            if (result > 0)
            {
                return _ResultHelper.BuildActionSuccess();
            }
            else
            {
                return _ResultHelper.BuildActionError();
            }
        }

        public async Task<RM_ApiResult> Deleted(int id)
        {
            await SoftDelete(id);
            return _ResultHelper.BuildActionSuccess();
        }

        public async Task<RM_ApiResult> GetPage(Par_AdminPageBase par)
        {
            var exp = Expressionable.Create<TCustomerinfo>()
                         .And(o => o.IsDeleted == false)
                         .AndIF(!string.IsNullOrWhiteSpace(par.KeyWord), o => SqlFunc.ToString(o.Id).Contains(par.KeyWord) || o.NickName.Contains(par.KeyWord) || o.Phone.Contains(par.KeyWord) || o.Email.Contains(par.KeyWord))
                         .ToExpression();

            var result = new RM_PageReturn<TCustomerinfo>
            {
                Datas = await _DbContext.Queryable<TCustomerinfo>().Where(exp).OrderByDescending(o => o.Id).ToPageListAsync(par.PageNo, par.PageSize),
                TotalCount = await _DbContext.Queryable<TCustomerinfo>().Where(exp).CountAsync(),
                PageNo = par.PageNo
            };

            result.Datas.ForEach(o =>
            {
                o.Password = null;
                o.StatusDesc = _EnumHelper.GetDescription((Enum_BaseStatus)o.Status);
                o.SexDesc = _EnumHelper.GetDescription((Enum_Sex)o.Sex);
            });

            return _ResultHelper.BuildSuccess(result);
        }

        #region 回收计划

        public async Task<RM_ApiResult> GetRecycleListByCustomerKey(Par_CustomerAsset par)
        {
            var result = new RM_PageReturn<TRecycleReq>();

            var exp = _DbContext.Queryable<TRecycleReq>()

            .WhereIF(par.CustomerKey > 0, o => o.CustomerId == par.CustomerKey)
            .WhereIF(par.BeginDate != null, o => o.CreateTime >= par.BeginDate)
            .WhereIF(par.EndDate != null, o => o.CreateTime <= par.EndDate);
            result.TotalCount = await exp.CountAsync();
            result.Datas = await exp.OrderByDescending(o => o.CreateTime).ToPageListAsync(par.PageNo, par.PageSize);
            result.Datas.ForEach(item =>
            {
                item.StatusDesc = _EnumHelper.GetDescription((Enum_RecycleStatus)item.Status);
            });

            return _ResultHelper.BuildSuccess(result);
        }

        #endregion 回收计划
    }
}